<template>
  <el-dialog
    v-model="dialogVisible"
    title="分配角色"
    width="500px"
    @close="handleClose"
  >
    <div class="role-assign">
      <div class="user-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ user?.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ user?.nickname }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="role-list">
        <h4>分配角色</h4>
        <el-checkbox-group v-model="selectedRoles" v-loading="loading">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
            :disabled="role.roleCode === 'SUPER_ADMIN' && user?.id !== 1"
          >
            {{ role.roleName }}
            <span class="role-code">({{ role.roleCode }})</span>
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/user'
import { roleApi } from '@/api/role'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  user: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

const loading = ref(false)
const saving = ref(false)
const roleList = ref([])
const selectedRoles = ref([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const loadRoles = async () => {
  try {
    loading.value = true
    const roles = await roleApi.getAllEnabledRoles()
    roleList.value = roles || []
  } catch (error) {
    console.error('加载角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadUserRoles = async () => {
  if (!props.user?.id) return
  
  try {
    const userWithRoles = await userApi.getUserById(props.user.id)
    selectedRoles.value = userWithRoles.roles?.map(role => role.id) || []
  } catch (error) {
    console.error('加载用户角色失败:', error)
  }
}

const handleClose = () => {
  dialogVisible.value = false
  selectedRoles.value = []
}

const handleSubmit = async () => {
  try {
    saving.value = true
    await userApi.assignRoles(props.user.id, selectedRoles.value)
    ElMessage.success('角色分配成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('分配角色失败:', error)
  } finally {
    saving.value = false
  }
}

watch(() => props.visible, (visible) => {
  if (visible) {
    loadRoles()
    loadUserRoles()
  }
})
</script>

<style scoped lang="scss">
.role-assign {
  .user-info {
    margin-bottom: 20px;
  }
  
  .role-list {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
    
    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .el-checkbox {
        margin-right: 0;
        
        .role-code {
          color: #909399;
          font-size: 12px;
          margin-left: 8px;
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>